package com.yxjx.duoxue.lbs;

import java.io.File;
import java.net.URISyntaxException;
import java.nio.channels.FileChannel.MapMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;

import org.apache.http.util.LangUtils;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.datamodel.DMBaiduLocation;
import com.yxjx.duoxue.datamodel.DMLocationPoint;
import com.yxjx.duoxue.datamodel.DMLocationPoints;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

public class LocationIndicatorActivity extends BaseActionBarActivity {

	MapView mMapView = null;
	private BaiduMap mBaiduMap;
	private boolean isFirstLoc = true;
	private MyLocationListenner myListener;
	private LocationClient mLocClient;
	HashMap<LatLng, Overlay> LatlngOverlayMap = new HashMap<LatLng, Overlay>();
	private ArrayList<DMLocationPoint> mLocPoints;
	private boolean isThirdNavInstalled;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 在使用SDK各组件之前初始化context信息，传入ApplicationContext
		// 注意该方法要再setContentView方法之前实现
		// SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.fragment_layout_lbs);
		customizeActionBarTitle("");
		
		isThirdNavInstalled = isThirdNavInstalled();
		// 获取地图控件引用
		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();
		// 普通地图
		mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
		// customize GPS and description
		Bundle extra = getIntent().getExtras();
		DMLocationPoints points = (DMLocationPoints) extra
				.getSerializable(Yx.KEY_MULTI_LOCATIONS);
		String pageTitle = extra.getString(Yx.KEY_PAGE_TITLE);
		customizeActionBarTitle(pageTitle);
		if (points == null) {
			// 单地址
			double lat = extra.getDouble(Yx.KEY_GPS_LAT);
			double log = extra.getDouble(Yx.KEY_GPS_LOG);
			String title = extra.getString(Yx.KEY_GPS_TITLE);
			addSingleMarker(log, lat, title);
			showTitle(log, lat, title);

		} else {
			// 多地址
			addMultiMarkers(points);
		}
		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		mLocClient = new LocationClient(this);

		myListener = new MyLocationListenner();
		mLocClient.registerLocationListener(myListener);
		LocationClientOption loption = new LocationClientOption();
		loption.setOpenGps(true);// 打开gps
		loption.setCoorType("bd09ll"); // 设置坐标类型
		loption.setScanSpan(1000);
		loption.setTimeOut(3000);
		loption.setLocationNotify(true);
		mLocClient.setLocOption(loption);
		mLocClient.start();
		
	}

	private void addMultiMarkers(DMLocationPoints points) {
		mLocPoints = points.getList();
		for (DMLocationPoint item : mLocPoints) {
			String[] posStr = item.getGps().split(",");
			double[] posDouble = new double[2];

			try {
				posDouble[0] = Double.valueOf(posStr[0]);
				posDouble[1] = Double.valueOf(posStr[1]);
			} catch (Exception e) {
				Utils.logd("LocationIndicatiorActivity parse GPS error，gps = "
						+ item.getGps());
				continue;
			}
			addSingleMarker(posDouble[0], posDouble[1], item.getAddress());
		}
		DMLocationPoint nearest = getNearestPoint(mLocPoints);
		double[] loglat = Utils.getLogLat(nearest.getGps());
		showTitle(loglat[0], loglat[1], nearest.getAddress());
	}

	private void addSingleMarker(double log, double lat, final String titleIn) {
		// 定义Maker坐标点
		LatLng point = new LatLng(lat, log);
		// 构建Marker图标
		BitmapDescriptor bitmap = BitmapDescriptorFactory
				.fromResource(R.drawable.map_address);
		// 构建MarkerOption，用于在地图上添加Marker
		OverlayOptions option = new MarkerOptions().position(point)
				.icon(bitmap);
		// 在地图上添加Marker，并显示
		final Overlay overlay = mBaiduMap.addOverlay(option);
		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
			@Override
			public boolean onMarkerClick(Marker arg0) {
				LatLng latlng = arg0.getPosition();
				String title = getTitle(latlng.longitude, latlng.latitude,
						mLocPoints);
				if (UIHelper.isEmpty(title)) {
					title = titleIn;
				}
				showTitle(latlng.longitude, latlng.latitude, title);

				return false;
			}
		});
	}

	private DMLocationPoint getNearestPoint(ArrayList<DMLocationPoint> points) {
		DMBaiduLocation myLoation = DMBaiduLocation.getLocation(this);
		if (points == null || points.size() == 0) {
			return null;
		} else if (points.size() == 1) {
			return points.get(0);
		} else {
			DMLocationPoint nearest;
			DMLocationPoint point = points.get(0);
			double[] loglat = Utils.getLogLat(point.getGps());
			double distance = Utils.GetDistance(loglat[1], loglat[0],
					myLoation.getLatitude(), myLoation.getLongtitude());
			nearest = point;

			for (int i = 1; i < points.size(); i++) {
				point = points.get(i);
				loglat = Utils.getLogLat(point.getGps());
				double dist = Utils.GetDistance(loglat[1], loglat[0],
						myLoation.getLatitude(), myLoation.getLongtitude());
				if (dist < distance) {
					nearest = point;
					distance = dist;
				}
			}

			return nearest;
		}
	}

	private void showTitle(final double log, final double lat,
			final String title) {
		// 创建InfoWindow展示的view
		Button button = new Button(getApplicationContext());
		button.setWidth(getResources().getDimensionPixelSize(
				R.dimen.map_ind_rect));
		button.setPadding(20, 20, 20, 20);
		button.setGravity(Gravity.CENTER);
		button.setBackgroundResource(R.drawable.map_address_bg);
		button.setText(title);

		View mapItem = LayoutInflater.from(this).inflate(
				R.layout.map_detailed_item, null);
		button.setWidth(getResources().getDimensionPixelSize(
				R.dimen.map_ind_rect));
		UIHelper.setText(mapItem, R.id.loc_desc, title);

		// 定义用于显示该InfoWindow的坐标点
		LatLng pt = new LatLng(lat, log);
		// 导航目标位置
		final DMBaiduLocation desLocation = new DMBaiduLocation();
		desLocation.setAddrStr(title);
		desLocation.setLatitude(lat);
		desLocation.setLongtitude(log);
		// 当前所在位置
		final DMBaiduLocation curLocation = DMBaiduLocation.getLocation(this);
		// 点击导航后的行为
		if (!isThirdNavInstalled) {
			mapItem.findViewById(R.id.loc_nav).setVisibility(View.GONE);
			mapItem.findViewById(R.id.loc_nav_divider).setVisibility(View.GONE);
		} else {
			UIHelper.setClickListener(mapItem, R.id.loc_nav,
					new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// 打开导航页面
					Intent intent1 = new Intent(
							LocationIndicatorActivity.this,
							NavActivity.class);
					intent1.putExtra(Yx.EXTRA_NAV_START, curLocation);
					intent1.putExtra(Yx.EXTRA_NAV_END, desLocation);
					// startActivity(intent1);
					tryCallThirdNav(curLocation, desLocation);
				}
			});
		}

		// 创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
		InfoWindow mInfoWindow = new InfoWindow(mapItem, pt, -80);
		// 显示InfoWindow
		mBaiduMap.showInfoWindow(mInfoWindow);
	}

	private String getTitle(double log, double lat,
			ArrayList<DMLocationPoint> items) {

		if (items == null || items.size() == 0) {
			return "";
		}
		for (DMLocationPoint item : items) {
			double[] loglat = Utils.getLogLat(item.getGps());
			if (Utils.GetDistance(loglat[1], loglat[0], lat, log) < 0.01) {
				return item.getAddress();
			}
		}
		return "";
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;
			Log.d("CMM", "receive new location" + location);
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				try {
					mBaiduMap.animateMapStatus(u);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		mLocClient.stop();
		mLocClient.unRegisterLocationListener(myListener);
		mMapView.onDestroy();

	}

	@Override
	protected void onResume() {
		super.onResume();
		// 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
		mMapView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
		mMapView.onPause();
	}

	/**
	 * 判断是否安装目标应用
	 * 
	 * @param packageName
	 *            目标应用安装后的包名
	 * @return 是否已安装目标应用
	 */
	private boolean isInstallByRead(String packageName) {
		return Utils.isAppInstalled(this, packageName);
//		return new File("/data/data/" + packageName).exists();
	}
	
	private boolean isThirdNavInstalled() {
		if (isInstallByRead("com.baidu.BaiduMap")) {
			Log.d("GasStation", "com.baidu.BaiduMap地图客户端已经安装");
			return true;
		} else if (isInstallByRead("com.autonavi.minimap")) {
			Log.d("GasStation", "com.autonavi.minimap地图客户端已经安装");
			return true;
		} 
		return false;
	}

	// 调起百度或者高德地图客户端
	private void tryCallThirdNav(DMBaiduLocation source, DMBaiduLocation dest) {
		try {
			Intent baiduIntent = Intent
					.getIntent("intent://map/direction?origin=latlng:"
							+ source.getLatitude()
							+ ","
							+ source.getLongtitude()
							+ "|name:我的位置&destination="
							+ "latlng:"
							+ dest.getLatitude()
							+ ","
							+ dest.getLongtitude()
							+ "|name:" + dest.getAddrStr()
							+ "&mode=driving&region=&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
			
			Intent gaodeIntent = Intent
					.getIntent("androidamap://path?sourceApplication=duoxue&sid=BGVIS1&slat="
							+ source.getLatitude()
							+ "&slon="
							+ source.getLongtitude()
							+ "&sname="
							+ "我的位置"
							+ "&did=BGVIS2&dlat="
							+ dest.getLatitude()
							+ "&dlon="
							+ dest.getLongtitude()
							+ "&dname="
							+ dest.getAddrStr() + "&dev=1&m=2&t=0");
			// 上面的高德地图URI文法有错误
//			gaodeIntent = new Intent("android.intent.action.VIEW", android.net.Uri.parse("androidamap://navi?sourceApplication=多学&lat=" + dest.getLatitude()+ "&lon="+ dest.getLongtitude() + "&dev=0"));
			gaodeIntent = new Intent("android.intent.action.VIEW", android.net.Uri.parse("androidamap://viewMap?sourceApplication=多学&poiname=" + dest.getAddrStr() + "&lat=" + dest.getLatitude() + "&lon=" + dest.getLongtitude() + "&dev=0"));
			gaodeIntent.setPackage("com.autonavi.minimap");
			
			try {
				if (isInstallByRead("com.baidu.BaiduMap")) {
					Log.d("GasStation", "百度地图客户端已经安装");
					startActivity(baiduIntent); // 启动调用
				} else if (isInstallByRead("com.autonavi.minimap")) {
					Log.d("GasStation", "高德地图客户端已经安装");
					startActivity(gaodeIntent); // 启动调用
				} else {
					Log.d("GasStation", "没有安装百度地图客户端或者高德地图客户端");
				}
			} catch (Exception e) {
				// walkround to skip exception
			}
			
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}

}
